package com.znzz.course.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.*;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import com.znzz.course.R;
import com.znzz.course.entity.Course;
import com.znzz.course.util.ConnByHttp;
import com.znzz.course.util.db.CourseDao;
import com.znzz.course.util.db.StudentDao;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Array;
import java.util.ArrayList;

/**
 * 学期学年选择功能模块
 * 用于添加对应年级的课程信息
 */
public class TermChoiceActivity extends AppCompatActivity {
    //下拉框
    private Spinner spinner_semester_data,spinner_time_data;
    private Button okButton,reButton;
    String semester_num,time_num,semester,time;
    //学年学期适配器
    private ArrayAdapter<String> semester_adapter,time_adapter;
    Handler handler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_term_choice);
        setFinishOnTouchOutside(false);
        initView();
        //初始化课表内容
        handler = new Handler(){
            @Override
            public void handleMessage(@NonNull Message msg) {
                super.handleMessage(msg);
                switch (msg.what){
                    case 1:
                        //从后端数据库导入课表
                        String result = msg.obj.toString();
                        //判断是否返回空数据
                        if (!result.equals("")){
                            CourseDao courseDao = new CourseDao(TermChoiceActivity.this);
                            if(courseDao.loadData()!=null){
                                //不为空，先删除本地导入学期的课程信息
                                courseDao.deleteAllCourse();
                            }
                            try {
                                //重新把数据库拿去的数据分析，封装，保存
                                JSONObject jsonObject1 = new JSONObject(result);
                                JSONArray jsonArray = jsonObject1.getJSONArray("courses");
                                for(int i=0;i<jsonArray.length();i++){
                                    JSONObject jsonObject = (JSONObject) jsonArray.get(i);
                                    Course course = new Course();
                                    course.setClassEnd(Integer.parseInt(jsonObject.getString("clazzEnd")));
                                    course.setClassRoom(jsonObject.getString("clazzRoom"));
                                    course.setClassStart(jsonObject.getInt("clazzStart"));
                                    course.setCourseName(jsonObject.getString("courseId"));
                                    course.setDay(jsonObject.getInt("day"));
                                    course.setTeacher(jsonObject.getString("teacherId"));
                                    course.setWeekEnd(jsonObject.getInt("weekEnd"));
                                    course.setWeekStart(jsonObject.getInt("weekStart"));
                                    //存储数据到数据库
                                    courseDao.saveData(course);
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            Intent intent = new Intent(TermChoiceActivity.this,MainActivity.class);
                            startActivityForResult(intent,7);
                            Toast.makeText(TermChoiceActivity.this,"导入成功",Toast.LENGTH_LONG).show();
                            finish();
                        }else{
                            Toast.makeText(TermChoiceActivity.this,"导入失败",Toast.LENGTH_LONG).show();
                        }
                        break;
                }
            }
        };

        // 建立数据源
        ArrayList semester_list =new ArrayList<>();
        semester_list.add("大一");
        semester_list.add("大二");
        semester_list.add("大三");
        semester_list.add("大四");
        // 建立Adapter并且绑定数据源
        semester_adapter =new ArrayAdapter<String>(TermChoiceActivity.this,android.R.layout.simple_spinner_item,
                semester_list);
        //设置下拉列表的风格,simple_spinner_dropdown_item是android系统自带的样式，等会自定义修改
        //将可选内容与ArrayAdapter连接起来，simple_spinner_item是android系统自带样式groupScene_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        //绑定 Adapter到控
        spinner_semester_data.setAdapter(semester_adapter);
        //添加事件Spinner事件监听
        spinner_semester_data.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view,
                                       int pos, long id) {
                semester = spinner_semester_data.getSelectedItem().toString();
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                // Another interface callback
            }
        });

        ArrayList time_list =new ArrayList<>();
        time_list.add("上期");
        time_list.add("下期");
        time_adapter =new ArrayAdapter<String>(TermChoiceActivity.this,android.R.layout.simple_spinner_item,
                time_list);
        spinner_time_data.setAdapter(time_adapter);
        //添加事件Spinner事件监听
        spinner_time_data.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view,
                                       int pos, long id) {
                time= spinner_time_data.getSelectedItem().toString();
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                // Another interface callback
            }
        });

        reButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        okButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (semester=="大一"){
                    semester_num = "1";
                }
                if (semester=="大二"){
                    semester_num = "2";
                }
                if (semester=="大三"){
                    semester_num = "3";
                }
                if (semester=="大四"){
                    semester_num = "4";
                }
                if (time=="上期"){
                    time_num = "1";
                }
                if (time=="下期"){
                    time_num = "2";
                }
                //拼接数据库的学年期字段
                String semester_all = semester_num+time_num;
//                Toast.makeText(TermChoiceActivity.this,semester+time,Toast.LENGTH_SHORT).show();
//                Toast.makeText(TermChoiceActivity.this,semester_all,Toast.LENGTH_SHORT).show();
                StudentDao studentDao = new StudentDao(TermChoiceActivity.this);
                //获取登陆学生的学号
                String studentId = studentDao.loadData().getStudentId();
                initialize(studentId,semester_all);
                finish();
            }
        });

    }

    public void initView(){
        spinner_semester_data = findViewById(R.id.spinner_semester);
        spinner_time_data = findViewById(R.id.spinner_time);
        okButton = findViewById(R.id.okButton);
        reButton =findViewById(R.id.reButton);
    }

    //初始化课表信息
    public void initialize(String studentId,String semester){
        Intent intent =getIntent();
        studentId = intent.getStringExtra("studentId");
        //防止跳转之后参数重置，这时候去导入课表为空
        if(studentId==null||studentId==""){
            StudentDao studentDao = new StudentDao(TermChoiceActivity.this);
            studentId = studentDao.loadData().getStudentId();
        }
        String url =
                "http://192.168.92.1:8123/courseServer/getCourseByStudentId?studentId="+studentId+"&semesterId="+semester;
        //启动子线程
        ConnByHttp connByHttp=new ConnByHttp(url,handler);
        connByHttp.start();
    }
}